package com.efeichong.common.utils;

import com.efeichong.common.domain.ResponseData;
import com.efeichong.common.utils.json.JsonUtils;
import com.google.common.base.Charsets;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.entity.ContentType;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author lxk
 * @date 2020/9/2
 * @description 将返回数据通过流传给前端
 */
@Slf4j
public class ResponseUtils {

    public static void format(HttpServletResponse httpServletResponse, ResponseData responseData) {
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json");
        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
        try {
            httpServletResponse.getWriter().println(JsonUtils.toJson(responseData));
            httpServletResponse.getWriter().flush();
        } catch (IOException e) {
            e.printStackTrace();
            log.error("HttpServletResponse返回错误:", e);
        }
    }

    public static void format(HttpServletResponse httpServletResponse, HttpServletRequest request, ResponseData responseData) {
        httpServletResponse.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        httpServletResponse.setHeader("Access-Control-Max-Age", "3600");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", "x-requested-with,Authorization");
        httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
        httpServletResponse.setCharacterEncoding(Charsets.UTF_8.name());
        httpServletResponse.setContentType(ContentType.APPLICATION_JSON.getMimeType());
        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
        try {
            httpServletResponse.getWriter().println(JsonUtils.toJson(responseData));
            httpServletResponse.getWriter().flush();
        } catch (IOException e) {
            e.printStackTrace();
            log.error("HttpServletResponse返回错误:", e);
        }
    }

}
